<?php

namespace app\api\controller;

use app\admin\model\Config;
use app\attachment\controller\ApiUpload as Upload;
use app\common\controller\ApiBase;
use app\Constant\ApiConstant;
use app\model\AgentDistribution;
use app\model\DistributionSetting;
use app\model\Order;
use app\model\Poster;
use app\model\User as UserModel;
use app\model\UserBalanceLog;
use app\model\UserBalanceWithdrawalLogModel;
use app\model\UserInvite;
use app\model\UserInviteUpdateLogModel;
use app\model\UserOauth;
use app\model\UserUpgradeLogModel;
use app\model\Withdrawal;
use app\model\WithdrawalAuto;
use app\service\UserService;
use app\service\WxPayService;
use Random\RandomException;
use think\Db;
use think\Exception;
use think\facade\Log;
use think\facade\Request;
use think\response\Json;
use Throwable;
use util\Logger;
use Wechat\CommerceApp;
use Wechat\MiniApp;

class User extends ApiBase
{
	private UserModel $user;

	protected function initialize()
	{
		parent::initialize();
		if (!empty($this->token)) {
			$user = UserModel::field('id, user_secret, token, nickname, mobile, vip_expire_time, parent_user_id, agent_id, invite_count, order_count, chat_count, total, money, avatar, bind_status, area_code, level, code, is_new, is_real, name, idcard')
				->where('token', $this->token)
				->find();
			if (empty($user)) {
				$this->callbackAndExit(ApiConstant::NO_LOGIN, '用户未登录');
			}
			$token_check = $this->checkUserToken($this->token);
			if ($token_check !== true) {
				$this->callbackAndExit(ApiConstant::NO_LOGIN, $token_check);
			}
			$this->user = $user;
		}
	}

	/**
	 * 小程序登录
	 *
	 * @return Json
	 */
	public function login()
	{
		$user = $oauth = [];
		try {
			$code        = Request::param('code');
			$invite_code = Request::param('invite_code'); //邀请码
			Logger::error('获取配置失败' . $invite_code);
			$app         = MiniApp::getInstance();
			$login_data  = $app->getSession($code);
			$session_key = $login_data['session_key'];
			$openid      = $login_data['openid'];
			$unionid     = $login_data['unionid'] ?? '';

			$provider = 'WeChat';
			$platform = 'wxMiniProgram';
			//判断是否已经注册
			$user_info = UserService::getUserInfo($openid, $platform);
			if ($user_info) {
				UserModel::where('token', $user_info['token'])->update([
					'login_time' => time(),
					'login_ip'   => request()->ip(1),
				]);
				//更新授权信息
				$access_info = UserOauth::where('openid', $openid)->value('access_info');
				if ($access_info) {
					$access_info          = json_decode($access_info, true);
					$access_info['login'] = $login_data;
					UserOauth::where('openid', $openid)->update([
						'access_info' => json_encode($access_info, JSON_UNESCAPED_UNICODE),
					]);
				}
				return $this->callback(ApiConstant::SUCCESS, '登录成功', $user_info);
			}

			Db::startTrans();
			//获取用户信息
			try {
				// 设置注册锁
				if (!UserService::lockRegister($openid)) {
					throw new Exception('频繁请求，请稍后重试～');
				}

				// 如果没有邀请人，则自动将牛总的账号当作为邀请人
				$invite_token   = 'gjuGrkkZRau3kIyd';
				$invite_user_id = 1;
				$agent_id       = 0;
				$invite_type    = 1;
				if ($invite_code) {
					if (!is_numeric($invite_code)) {
						$invite_user = UserModel::field('id, token, agent_id')->where('code', $invite_code)->where('status', 1)->find();
						if ($invite_user) {
							$invite_type    = 0;
							$invite_token   = $invite_user['token'];
							$invite_user_id = $invite_user['id'];
							$agent_id       = $invite_user['agent_id'];
						}
					} else {
						$agent_id = intval($invite_code);
					}
				}

				$data = UserService::saveUser($openid, $unionid, $provider, $platform, [], $login_data, $invite_type, $invite_user_id, $invite_token, $agent_id);
				Db::commit();
				//执行注册推客
				try {
					CommerceApp::getInstance()->RegisterAndBind($openid);
				} catch (\Exception $e) {
				}

				// 解除注册锁
				UserService::unlockRegister($openid);
				return $this->callback(ApiConstant::SUCCESS, 'success', $data);
			} catch (\Exception $e) {
				Db::rollback();
				Logger::error($e->getMessage(), [
					'file'  => $e->getFile(),
					'line'  => $e->getLine(),
					'msg'   => $e->getMessage(),
					'code'  => $code,
					'user'  => $user,
					'oauth' => $oauth,
				]);
				// 解除注册锁
				UserService::unlockRegister($openid);
				return $this->callback(ApiConstant::FAILURE, '授权失败');
			}
		} catch (\Exception $e) {
			Logger::error($e->getMessage(), [
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'code' => $code ?? '',
			]);
			return $this->callback(ApiConstant::FAILURE, '授权失败');
		}
	}

	/**
	 * 注册并绑定机构成为推客
	 *
	 * @return Json
	 */
	public function register_tk()
	{
		$user = UserModel::field('id, bind_status')->where('token', $this->token)->find();
		if (!$user) {
			return $this->callback(ApiConstant::NO_LOGIN, '用户未登录');
		}
		if ($user['bind_status'] == 1) {
			return $this->callback(ApiConstant::FAILURE, '账号已绑定机构');
		}
		try {
			$openid = UserOauth::where('user_id', $user['id'])->value('openid');
			$res    = CommerceApp::getInstance()->RegisterAndBind($openid);
			if ($res['register_status'] != 2) {
				$msg = '账号未注册完成';
				if ($res['register_status'] == 1) {
					$msg = '账号注册中';
				} elseif ($res['register_status'] == 3) {
					$msg = '微信需要支付实名才能注册';
				}
				return $this->callback(ApiConstant::FAILURE, $msg, $res);
			}
			if ($res['bind_status'] == 1) {
				DB::transaction(function () use ($res) {
					// 更新绑定状态
					UserModel::where('token', $this->token)->update([
						'sharer_appid' => $res['sharer_appid'],
						'bind_status'  => 1,
					]);

					if (!empty($this->user['mobile'])) {
						// 注册奖励佣金 (满足条件 1.绑定手机号 2.绑定机构成为推客)
						UserService::reward($this->user['parent_user_id'], $this->user['id']);
					}
				});

				return $this->callback(ApiConstant::SUCCESS, '绑定成功');
			}
			return $this->callback(ApiConstant::SUCCESS, 'success', [
				'queryString'       => $res['bind_query_string'],
				'headSupplierAppid' => $res['appid'],
			]);
		} catch (\Exception $e) {
			Logger::error($e->getMessage(), [
				'file' => $e->getFile(),
				'line' => $e->getLine(),
			]);
			return $this->callback(ApiConstant::FAILURE, '程序异常');
		}
	}

	/**
	 * 绑定手机号
	 *
	 * @return Json
	 */
	public function bind_phone()
	{
		$code = Request::post('code');
		try {
			if (!empty($this->user['mobile'])) {
				return $this->callback(ApiConstant::FAILURE, '手机号已绑定');
			}
			$res = MiniApp::getInstance()->getPhoneNumber($code);

			// 判断手机号是否已经被绑定
			$userInfoByPhone = UserModel::where('mobile', $res['phoneNumber'])->find();
			if (!empty($userInfoByPhone)) {
				return $this->callback(ApiConstant::FAILURE, '手机号已被绑定，请更换其他手机号码');
			}
			DB::startTrans();
			$user_res = UserModel::where('token', $this->token)
				->update([
					'mobile'    => $res['phoneNumber'],
					'area_code' => $res['countryCode'],
				]);
			if ($user_res) {
				if ($this->user['bind_status'] == UserModel::BIND_STATUS_YES) {
					// 注册奖励佣金 (满足条件 1.绑定手机号 2.绑定机构成为推客)
					UserService::reward($this->user['parent_user_id'], $this->user['id']);
				}
				DB::commit();
				return $this->callback(ApiConstant::SUCCESS, '绑定成功');
			} else {
				DB::rollback();
				return $this->callback(ApiConstant::FAILURE, '绑定失败');
			}
		} catch (\Exception $e) {
			Logger::error($e->getMessage(), [
				'file' => $e->getFile(),
				'line' => $e->getLine(),
			]);
			return $this->callback(ApiConstant::FAILURE, $e->getMessage());
		}
	}

	/**
	 * 获取用户信息
	 *
	 * @return Json
	 */
	public function info()
	{
		$user          = $this->user;
		$user['money'] = number_format($user['money'] > 0 ? $user['money'] / 100 : 0, 2);
		unset($user['vip_expire_time']);
		$setting              = DistributionSetting::getLevelInfo($user['level']);
		$user['distribution'] = $setting;
		$user['avatar']       = uploads_url() . $user['avatar'];
		$user['p_user']       = [];
		if ($user['parent_user_id'] > 0) {
			$userModel = new UserModel();
			$p_user    = $userModel->field('id, token, nickname, mobile, avatar, level')->where('id', $user['parent_user_id'])->find();
			if ($p_user) {
				$p_user['avatar'] = uploads_url() . $p_user['avatar'];
				$user['p_user']   = $p_user;
			}
		}
		$user['month_order_count']  = 0;
		$user['month_invite_count'] = 0;
		if ($user['level'] == 2) {
			// 查询升级记录
			$userUpgradeLog = UserUpgradeLogModel::field('id,source_type,created_at')
				->where('user_id', $user['id'])
				->where('type', UserUpgradeLogModel::TYPE_UPGRADE)
				->where('before_level', UserModel::LEVEL_V1)
				->where('after_level', UserModel::LEVEL_V2)
				->find()
				->toArray();

			$month = date('Ymd', strtotime($userUpgradeLog['created_at']));

			$info = DistributionSetting::field('id, type, value')->where('uuid', 'setting')->find();
			if ($info) {
				$value = json_decode($info['value'], true);

				$v2OrderCount  = $value[1]['order_count'];
				$v2InviteCount = $value[1]['invite_count'];

				$user['month_order_count']  = (new Order())->whereTime('create_time', 'month')->where('user_id', '=', $user['id'])->where('commission_status', '=', 100)->count();
				$user['month_invite_count'] = (new UserInvite())->whereTime('create_time', 'month')->where('token', '=', $user['token'])->count();

				if ($month == date('Ymd')) {
					if ($userUpgradeLog['source_type'] == UserUpgradeLogModel::SOURCE_TYPE_INVITE_UPGRADE) {
						$user['month_invite_count'] -= $v2InviteCount;
					}

					if ($userUpgradeLog['source_type'] == UserUpgradeLogModel::SOURCE_TYPE_CRATE_ORDER_UPGRADE) {
						$user['month_order_count'] -= $v2OrderCount;
					}
				}
			}

		} else {
			$user['month_order_count']  = (new Order())->whereTime('create_time', 'month')->where('user_id', '=', $user['id'])->where('commission_status', '=', 100)->count();
			$user['month_invite_count'] = (new UserInvite())->whereTime('create_time', 'month')->where('token', '=', $user['token'])->count();
		}

		return $this->callback(ApiConstant::SUCCESS, 'success', $user);
	}

	/**
	 * 修改个人信息（头像昵称）
	 *
	 * @return mixed
	 */
	public function personal()
	{
		$avatar    = Request::post('avatar');
		$nickname  = Request::post('nickname');
		$user      = $this->user;
		$userModel = new UserModel();
		if ($avatar) {
			$user_res = $userModel->where('id', $user['id'])
				->update([
					'avatar' => $avatar,
				]);
		}

		if ($nickname) {
			$user_res = $userModel->where('id', $user['id'])
				->update([
					'nickname' => $nickname,
				]);
		}

		return $this->callback(ApiConstant::SUCCESS, '修改成功');
	}

	/**
	 * 实名认证
	 *
	 * @return mixed
	 */
	public function real_name()
	{
		$name      = Request::post('name');
		$idcard    = Request::post('idcard');
		$user      = $this->user;
		$userModel = new UserModel();

		if (empty($name) || empty($idcard)) {
			return $this->callback(ApiConstant::FAILURE, '请完善实名信息');
		}

		$info = $userModel->where('idcard', $idcard)->find();
		if (!empty($info)) {
			return $this->callback(ApiConstant::FAILURE, '身份证信息已存在');
		}
		$level    = $user['level'] > 2 ? $user['level'] : 2;
		$user_res = $userModel->where('id', $user['id'])
			->update([
				'name'    => $name,
				'idcard'  => $idcard,
				'is_real' => 1,
				'level'   => $level,
			]);

		if ($user_res) {
			return $this->callback(ApiConstant::SUCCESS, '实名成功');
		} else {
			return $this->callback(ApiConstant::FAILURE, '实名失败');
		}

	}

	public function logout()
	{
		return $this->callback(ApiConstant::SUCCESS, '退出成功');
	}

	/**
	 * 邀请好友
	 *
	 * @return Json
	 */
	public function invite()
	{
		$user = $this->user;

		//海报背景图
		$bg_imgs = Poster::field('id, image')
			->withAttr('image', function ($value) {
				return $value ? get_file_path($value, 1) : '';
			})
			->where('status', 1)
			->order('sort', 'asc')
			->order('id', 'asc')->select()->toArray();
		$bg_imgs = array_column($bg_imgs, 'image');

		$qrcode = UserOauth::where('user_id', $user['id'])->value('qrcode');
		if (!empty($qrcode)) {
			return $this->callback(ApiConstant::SUCCESS, 'success', [
				'code'    => $user['code'],
				'qrcode'  => $qrcode,
				'bg_imgs' => $bg_imgs,
			]);
		}
		try {
			// 把二维码上传到云存储
			$upload_path = config('upload_path');
			$filepath    = 'qrcode';
			$qrcodePath  = $upload_path . '/' . $filepath . '/';
			if (!file_exists($qrcodePath)) {
				mkdir($qrcodePath, 0755, true);
			}
			$filename = $user['code'] . '.png';
			$filePath = $qrcodePath . $filename;

			$imageData = MiniApp::getInstance()->createQRCode('pages/index/index', "code={$user['code']}");
			if (empty($imageData)) {
				return $this->callback(ApiConstant::FAILURE, '获取二维码失败');
			}
			// 保存文件
			if (!file_put_contents($filePath, $imageData)) {
				return $this->callback(ApiConstant::FAILURE, '生成二维码失败');
			}
			//获取上传驱动
			$driver = Config::where('name', 'upload_driver')->value('value');
			$file   = $qrcodePath . '/' . $filename;
			if ($driver != 'local') {
				//把图片上传到第三方存储
				$upload   = new Upload();
				$oss_file = $upload->upload_local_file($filename, $filepath, $file); //值为空本地文件
				//删除本地文件
				if ($oss_file) {
					@unlink($file);
				}
			} else {
				$oss_file = request()->domain() . '/uploads/' . $filepath . '/' . $filename;
			}
			UserOauth::where('user_id', $user['id'])->update(['qrcode' => $oss_file]);
			return $this->callback(ApiConstant::SUCCESS, 'success', [
				'code'    => $user['code'],
				'qrcode'  => $oss_file,
				'bg_imgs' => $bg_imgs,
			]);
		} catch (\Exception $e) {
			return $this->callback(ApiConstant::FAILURE, $e->getMessage());
		}
	}

	/**
	 * 我的收益
	 *
	 * @return Json
	 */
	public function income()
	{
		$user = $this->user;
//        $res  = [
//            'total'      => $user['money'] > 0 ? number_format($user['money'] / 100, 2) : "0.00",
//            'today'      => "0.00",
//            'yesterday'  => "0.00",
//            'month'      => "0.00",
//            'last_month' => "0.00",
//        ];
		$UserBalanceLog = new UserBalanceLog();

		// 需求改动，把未结算的订单金额也算进去
//		$log   = $UserBalanceLog->where('user_id', '=', $user['id'])->where('status', '=', 100)->select();
		$log   = $UserBalanceLog->where('user_id', '=', $user['id'])
			->whereIn('status', [
				UserBalanceLog::STATUS_WAIT,
				UserBalanceLog::STATUS_COMPLETED,
			])
			->select();
		$data  = ['1' => 0, '2' => 0, '3' => 0, '4' => 0, '5' => 0];
		$count = 0;
		foreach ($log as $value) {
			$data[$value['scene']] += $value['money'];
			if ($value['scene'] == 1) {
				$count += 1;
			}
		}

		$unsettledTotal = UserBalanceLog::where('user_id', $user['id'])
			->where('scene', UserBalanceLog::SCENE_SHARE_ORDER)
			->where('status', UserBalanceLog::STATUS_WAIT)
			->sum('money');

		// 累计奖励 = 已到账 + 未到账
		$total = ($user['total'] / 100) + floatval($unsettledTotal);
		$total = $total <= 0 ? "0.00" : strval($total);

		// 需求要求：激励奖励为 注册激励奖励 + 粉丝下单平台奖励 总金额
		$jlReward = $data[2] + $data[4];

		$res = [
			'total'         => $total,
			'team_reward'   => $data[5] ? strval($data[5]) : "0.00",
			'jl_reward'     => $jlReward ? strval($jlReward) : "0.00",
			'invite_reward' => $data[3] ? strval($data[3]) : "0.00",
			'invite_count'  => $user['invite_count'],
			'pay_reward'    => $data[1] ? strval($data[1]) : "0.00",
			'pay_count'     => $count,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	/**
	 * 提交提现
	 *
	 * @return Json
	 * @throws RandomException
	 */
	public function submit_withdrawal()
	{
		$name             = Request::post('name');
		$withdrawal_money = Request::post('money');
		$image            = Request::post('image', '');
		$type             = Request::post('type', 1);
		//判断是否设置自动提现
		$withdrawal_auto = Config::where('name', 'withdrawal_auto')->value('value');
		if (empty($name) || empty($withdrawal_money)) {
			return $this->callback(ApiConstant::FAILURE, '请求参数错误');
		}
		if (!$withdrawal_auto && empty($image)) {
			return $this->callback(ApiConstant::FAILURE, '请上传收款码');
		}
		if ($withdrawal_auto && empty($type)) {
			return $this->callback(ApiConstant::FAILURE, '请选择提现方式');
		}
		$user = $this->user;

		//提现手续费配置
		$withdrawal           = Config::where('group', 'withdrawal')->where('status', 1)->column('name, value');
		$withdrawal_charge    = intval($withdrawal['withdrawal_charge']);
		$withdrawal_price_min = $withdrawal['withdrawal_price_min'];
		if ($withdrawal_price_min > $withdrawal_money) {
			return $this->callback(ApiConstant::FAILURE, '提现金额不能小于最低提现金额');
		}
		$withdrawal_money = $withdrawal_money * 100; //单位：分
		//手续费
		$charge_money = $withdrawal_money * $withdrawal_charge / 100;

		//判断是否满足提现条件
		if ($user['money'] - $withdrawal_money < 0) {
			return $this->callback(ApiConstant::FAILURE, '提现金额不能超过可提现金额');
		}
		$account       = [
			'name'  => $name,
			'money' => $withdrawal_money,
			'image' => $image,
		];
		$user_money    = $user['money'];
		$money         = $withdrawal_money - $charge_money; //实际到账金额
		$auto_error    = $transfer_no = '';
		$status        = $withdrawal_status = $auto_status = 0;
		$transfer_data = [];
		//自动提现调用第三方转账接口
		if ($withdrawal_auto) {
			//type: 提现类型，1：微信，2：支付宝，3：银行卡
			switch ($type) {
				case 1:
					$openid = UserOauth::where('user_id', $user['id'])->value('openid');
					try {
						$transfer_no       = buildOrderNo();
						$transfer_data     = WxPayService::getInstance()->transferV2(
							$transfer_no,
							$money,
							$openid,
							$name
						);
						$auto_status       = 0;
						$status            = 1;
						$withdrawal_status = 4;
					} catch (\Exception $e) {
						$auto_error = $e->getMessage();
						Logger::error('自动提现失败', [
							'error' => $e->getMessage(),
							'line'  => $e->getLine(),
							'file'  => $e->getFile(),
						]);
					}
					break;
				default:
					$auto_error = '暂不支持该方式自动提现';
			}
		}

		Db::startTrans();
		$time     = time();
		$res      = Withdrawal::create([
			'user_id'           => $user['id'],
			'type'              => 1,
			'name'              => $name,
			'withdrawal_money'  => $withdrawal_money,
			'money'             => $money,
			'withdrawal_charge' => $withdrawal_charge,
			'charge_money'      => $charge_money,
			'image'             => $image,
			'account'           => json_encode($account, JSON_UNESCAPED_UNICODE),
			'channel'           => 1, //todo: 目前没有用到该字段
			'status'            => $status,
			'withdrawal_status' => $withdrawal_status,
			'year'              => date('Y', $time),
			'month'             => date('n', $time),
			'day'               => date('j', $time),
			'before_money'      => $user_money,
			'after_money'       => $user_money - $withdrawal_money,
		]);
		$user_res = UserModel::where('id', $user['id'])->update([
			'money' => $user_money - $withdrawal_money,
		]);
		$auto_res = true;
		if ($withdrawal_auto) {
			$auto_res = WithdrawalAuto::create([
				'user_id'          => $user['id'],
				'withdrawal_id'    => $res->id,
				'order_no'         => $transfer_no,
				'transfer_bill_no' => $transfer_data['transfer_bill_no'] ?? '',
				'type'             => $type,
				'money'            => $money,
				'status'           => $auto_status,
				'msg'              => $auto_error,
			]);
		}
		if ($res && $user_res && $auto_res) {
			Db::commit();
			return $this->callback(ApiConstant::SUCCESS, '操作成功', $transfer_data);
		}
		Db::rollback();
		return $this->callback(ApiConstant::FAILURE, '操作失败');
	}

	/**
	 * 提现记录
	 *
	 * @return Json
	 * @throws RandomException
	 */
	public function withdrawal_record()
	{
		$page      = Request::get('page', 1);
		$page_size = Request::get('page_size', 10);
		$date      = Request::get('date');
		$user_id   = $this->user['id'];

		$query = Withdrawal::field('id, name, image, channel, account, withdrawal_money, money, withdrawal_charge, charge_money, status, withdrawal_status, remark, create_time')
			->where('user_id', $user_id)->where('type', 1);
		if ($date) {
			$date_arr = explode('-', $date);
			if ($date_arr) {
				$year  = $date_arr[0];
				$month = $date_arr[1];
				$query->where('year', $year)->where('month', $month);
			}
		}
		$total = $query->count();
		$lists = $query
			->withAttr('withdrawal_money', function ($value) {
				return $value ? $value / 100 : 0;
			})
			->withAttr('money', function ($value) {
				return $value ? $value / 100 : 0;
			})
			->withAttr('charge_money', function ($value) {
				return $value ? $value / 100 : 0;
			})
			->append()
			->order('id', 'desc')
			->page($page, $page_size)
			->select()->toArray();

		$text            = Withdrawal::$statusList;
		$withdrawal_text = Withdrawal::$withdrawalList;
		foreach ($lists as &$item) {
			$item['status_text']            = $text[$item['status']];
			$item['withdrawal_status_text'] = $withdrawal_text[$item['withdrawal_status']];
		}
		$res = [
			'total' => $total,
			'list'  => $lists,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	public function fans()
	{
		//总邀请人数
		$total_invite = UserInvite::where('token', $this->user['token'])->count();
		//今天邀请人数
		$day_invite = UserInvite::where('token', $this->user['token'])
			->whereTime('create_time', 'today')
			->count();
		//昨日邀请人数
		$yesterday_invite = UserInvite::where('token', $this->user['token'])
			->whereTime('create_time', 'yesterday')
			->count();
		$res              = [
			'total_invite'     => $total_invite,
			'day_invite'       => $day_invite,
			'yesterday_invite' => $yesterday_invite,
			'total'            => 0,
			'list'             => [],
		];

		$page      = Request::get('page', 1);
		$page_size = Request::get('page_size', 10);
		$type      = Request::get('type', 0); //0:全部，1：仅看有效
		$query     = UserInvite::field('iv.id, iv.create_time, u.token, u.nickname, u.avatar, u.level, u.create_time, u.is_new, u.bind_status, u.mobile')
			->alias('iv')
			->leftJoin('user u', 'u.id = iv.user_id')
			->where('iv.token', $this->user['token']);
		if ($type) {
			$query->where('u.is_new', 0);
		}
		$total = $query->count();
		$lists = $query->order('iv.id desc')
			->page($page, $page_size)
			->select()->toArray();
		if ($lists) {
			$res['total'] = $total;
			$level_info   = DistributionSetting::where('uuid', 'setting')->value('value');
			if ($level_info) {
				$level_info = json_decode($level_info, true);
			}
			foreach ($lists as &$item) {
				$level_name = $level_icon = '';
				if ($item['bind_status'] == 1) {
//                    $key                = $item['level'] == 2 ? 1 : 0;
					$key        = $item['level'] - 1;
					$level_name = $level_info[$key]['name'];
					$level_icon = $level_info[$key]['icon'] ? get_file_path($level_info[$key]['icon'], 1) : '';
				}

				$item['taskStatus'] = 0;
				if ($item['bind_status'] == UserModel::BIND_STATUS_YES && $item['mobile'] != '') {
					$item['taskStatus'] = 1;
				}
				$item['avatar'] = get_file_path($item['avatar']);

				$item['level_name'] = $level_name;
				$item['level_icon'] = $level_icon;
				unset($item['level']);
			}
			$res['list'] = $lists;
		}
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	/**
	 * 获取订单列表
	 *
	 * @return Json
	 */
	public function orders()
	{
		$page      = Request::get('page', 1);
		$page_size = Request::get('page_size', 10);
		$status    = Request::get('type', 0); //0:全部，20：在路上，100：已结算，200：已失效
		$date      = Request::get('date', ''); //时间筛选， ''：全部，today：今日，yesterday：昨日，week：近七天，month：本月，last_month：上个月

		$query = Order::field('id, order_id, goods_id, title, total, actual_commission, commission, subsidy_commission, commission_status, is_free, create_time, image')
			->where('user_id', $this->user['id']);
		if ($date) {
			switch ($date) {
				case 'today': //今日
					$query->whereTime('create_time', 'today');
					break; //昨日
				case 'yesterday':
					$query->whereTime('create_time', 'yesterday');
					break;
				case 'week': //近七天
					$query->whereTime('create_time', 'week');
					break;
				case 'month': //本月
					$query->whereTime('create_time', 'month');
					break;
				case 'last_month': //上个月
					$query->whereTime('create_time', 'last month');
					break;
			}
		}
		$sum_query = clone $query;
		if ($status) {
			$query->where('commission_status', $status);
		}
		$res = [
			'list' => [],
		];

		$total  = $query->count();
		$orders = $query
			->withAttr('total', function ($value) {
				return $value ? number_format($value / 100, 2) : 0;
			})
			->withAttr('commission', function ($value) {
				return $value ? number_format($value / 100, 2) : 0;
			})
			->order('id', 'desc')
			->page($page, $page_size)->select()->toArray();
		$sum_query->where('commission_status', 'in', [20, 100]);
		$total_income = $sum_query->sum('total') ?: 0;
		$income       = $sum_query->sum('commission') ?: 0;

		// 升级V3可得佣金金额
		$setting = AgentDistribution::getLevelInfo($this->user['agent_id'], 3, 1);
		foreach ($orders as &$item) {
			if ($setting) {
				$ratio                = $setting['ratio'] / 100;
				$v3Commission         = round($item['actual_commission'] * $ratio) + $item['subsidy_commission'];
				$item['v3Commission'] = number_format($v3Commission / 100, 2);
			}
		}

		if ($orders) {
			$res['list'] = $orders;
		}
		$res['order_count']  = $total;
		$res['income']       = $income > 0 ? number_format($income / 100, 2) : 0;
		$res['total_income'] = $total_income > 0 ? number_format($total_income / 100, 2) : 0;
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}


	/**
	 * 奖励明细
	 *
	 * @return mixed
	 */
	public function orders_income()
	{
		$UserBalanceLog = new UserBalanceLog();

		$page      = Request::get('page', 1);
		$page_size = Request::get('page_size', 10);
		$type      = Request::get('type', 0); //0:全部，1：分享赚，2：平台奖励，3：邀请奖励
		$order_id  = Request::get('order_id', ''); //订单筛选

		$query     = $UserBalanceLog->where('user_id', $this->user['id']);
		$sum_query = clone $query;
		if ($type) {
			if ($type == 2) {
				$query->where('scene', 'in', [2, 4, 5]);
				$sum_query->where('scene', 'in', [2, 4, 5]);
			} else {
				$query->where('scene', $type);
				$sum_query->where('scene', $type);
			}
		}

		if ($order_id) {
			$query->where('order_id', 'like', '%' . $order_id . '%');
		}
		$res = [
			'list' => [],
		];

		$unsettled_query = clone $sum_query;
		$settled_query   = clone $sum_query;
		$cancel_query    = clone $sum_query;

		$total  = $query->count();
		$orders = $query
			->order('log_id', 'desc')
			->page($page, $page_size)->select()->toArray();

		$income           = $sum_query->where('status', '<>', 200)->sum('money') ?: 0;
		$unsettled_income = $unsettled_query->where('status', '=', 20)->sum('money') ?: 0;
		$settled_income   = $settled_query->where('status', '=', 100)->sum('money') ?: 0;
		$cancel_income    = $cancel_query->where('status', '=', 200)->sum('money') ?: 0;
		if ($orders) {
			$res['list'] = $orders;
		}
		$res['order_count']      = $total;
		$res['income']           = $income;
		$res['unsettled_income'] = $unsettled_income;
		$res['settled_income']   = $settled_income;
		$res['cancel']           = $cancel_income;
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	/**
	 * 等级列表
	 *
	 * @return mixed
	 */
	public function levelInfo()
	{
		$info = (new DistributionSetting())->field('id, type, value, invite')->where('uuid', 'setting')->find();
		$res  = json_decode($info['value'], true);
		foreach ($res as $k => $v) {
			if (isset($res['order_count'])) {
				$res[$k]['order_count'] = intval($v['order_count']);
			}
			if (isset($res['invite_count'])) {
				$res[$k]['invite_count'] = intval($v['invite_count']);
			}
		}

//        if ($res && isset($res[2])) {
//            $res[2]['invite_num'] = $info['invite'] ?? 0;
//        }

		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	/**
	 * 领取佣金奖励
	 *
	 * @return Json
	 * @throws \Exception
	 * @throws Throwable
	 */
	public function receive()
	{
		Log::init([
			'type'      => 'file',
			'path'      => app()->getRootPath() . 'runtime/log/payQuery/',
			'level'     => ['info', 'error', 'sql', 'alert'],
			'max_files' => 10,
			'file_size' => 1024 * 1024 * 100,
		]);

		$user           = $this->user;
		$UserBalanceLog = new UserBalanceLog();

		$log = $UserBalanceLog->where('user_id', '=', $user['id'])
			->where('type', $UserBalanceLog::TYPE_REAL_TIME)
			->where('account_status', '=', 0)
			->find();

		$transfer_data = [];
		if ($log) {
			$openid = UserOauth::where('user_id', $user['id'])->value('openid');
			$money  = $log['money'] * 100;
			$name   = $user['nickname'];

			// 查询用户余额自动提现记录表
			$userBalanceWithdrawalLog = UserBalanceWithdrawalLogModel::field('id,order_no')
				->where('user_id', $user['id'])
				->where('user_balance_id', $log['log_id'])
				->where('status', UserBalanceWithdrawalLogModel::STATUS_WAIT)
				->find();
			if (empty($userBalanceWithdrawalLog)) {
				$createData = [
					'user_id'         => $user['id'],
					'user_balance_id' => $log['log_id'],
					'type'            => UserBalanceWithdrawalLogModel::TYPE_WECHAT,
					'order_no'        => buildOrderNo(),
					'money'           => $money,
					'status'          => UserBalanceWithdrawalLogModel::STATUS_WAIT,
					'created_at'      => date('Y-m-d H:i:s'),
					'updated_at'      => date('Y-m-d H:i:s'),
				];
				UserBalanceWithdrawalLogModel::create($createData);
				$transfer_no = $createData['order_no'];
			} else {
				$transfer_no = $userBalanceWithdrawalLog['order_no'];
			}

			try {
				// 查询是否有转账记录，
				try {
					$result = WxPayService::getInstance()->queryTransferOrder($transfer_no);

					$stateList = [
						'WAIT_USER_CONFIRM', 'TRANSFERING',
					];

					if (!in_array($result['state'], $stateList)) {
						switch ($result['state']) {
							case 'FAIL':
								Log::error(['已生成转账订单，转账订单状态为失败，订单信息为：', [$result]]);
								throw new Exception('转账订单异常');
							case 'SUCCESS':
								Log::error(['已生成转账订单，转账订单状态为成功，订单信息为：', [$result]]);
								throw new Exception('转账订单异常');
							default:
								Log::error(['已生成转账订单，转账订单状态异常，订单信息为：', [$result]]);
								throw new Exception('转账订单异常');
						}
					}
				} catch (Throwable $e) {
					if ($e->getCode() !== 404) {
						throw $e;
					}
				}
				$transfer_data = WxPayService::getInstance()->transfer(
					$transfer_no,
					$money,
					$openid,
					$name
				);
			} catch (\Exception $e) {
				Log::error('自动提现失败', [
					'error' => $e->getMessage(),
					'line'  => $e->getLine(),
					'file'  => $e->getFile(),
				]);
				Log::error('异常信息', [$e]);
			}
		}

		return $this->callback(ApiConstant::SUCCESS, '获取成功', $transfer_data);
	}


	/**
	 * 修改邀请人
	 *
	 * @return Json
	 */
	public function updateInviteUser(): Json
	{
		$userInfo = $this->user;

		$params = Request::param();

		if (empty($params['mobile']) || !validateMobile($params['mobile'])) {
			return $this->callback(ApiConstant::PARAM_ERROR, '手机号为空或格式不正确');
		}

		// 查询用户是否存在
		$parentUserInfo = UserModel::where('mobile', $params['mobile'])->find();
		if (empty($parentUserInfo)) {
			return $this->callback(ApiConstant::FAILURE, '要绑定的用户不存在');
		}

		// 查询当前用户是否邀请过用户注册
		$userInviteData = UserInvite::where('token', $userInfo['token'])->find();
		if (!empty($userInviteData)) {
			return $this->callback(ApiConstant::FAILURE, '您不满足更换邀请人条件!');
		}

		// 查询当前用户是否已经购买过订单
		$orderInfo = Order::where('user_id', $userInfo['id'])->find();
		if (!empty($orderInfo)) {
			return $this->callback(ApiConstant::FAILURE, '您不满足更换邀请人条件!');
		}

		// 无需变更
		if ($userInfo['parent_user_id'] == $parentUserInfo['id']) {
			return $this->callback(ApiConstant::FAILURE, '您不满足更换邀请人条件!');
		}

		// 去重新绑定用户
		DB::transaction(function () use ($userInfo, $parentUserInfo, $params) {
			// 修改用户邀请人
			UserModel::where('id', $userInfo['id'])->update([
				'parent_user_id' => $parentUserInfo['id'],
			]);

			// 修改用户邀请记录中的邀请人
			UserInvite::where('user_id', $userInfo['id'])->update([
				'token' => $parentUserInfo['token'],
			]);

			// 添加用户重新绑定记录
			UserInviteUpdateLogModel::create([
				'user_id'               => $userInfo['id'],
				'before_parent_user_id' => $userInfo['parent_user_id'],
				'after_parent_user_id'  => $parentUserInfo['id'],
				'created_at'            => date('Y-m-d H:i:s'),
				'updated_at'            => date('Y-m-d H:i:s'),
			]);
		});

		return $this->callback(ApiConstant::SUCCESS, '操作成功');
	}
}
